import json
from neo4j import GraphDatabase

"""
{
 'actor': ['万国鹏', '王婷', '沈凯', '徐小琴', '林晨', '魏星', '蒿怡帆', '蒿怡菲', '覃培军', '王昭',
           '张文斌', '林俭', '耿立树', '张喜来', '周鹏', '寇骏', '姜涛', '袁咏仪', '方中信', '刘伟强',
           '冯德伦', '吴彦祖', '尔冬升', '麦兆辉', '庄文强', '方平', '张静初', '许鞍华', '林更新', '蒋梦婕',
           '陆剑明'],
 'category': ['剧情', '喜剧'],
 'composer': ['尔冬升'],
 'cover': 'http://img3.douban.com/view/movie_poster_cover/lpst/public/p2252471054.jpg',
 'director': ['尔冬升'],
 'district': ['China_中国大陆'],
 'id': 25746375,
 'language': ['汉语普通话', '粤语', '浙江方言'],
 'length': 134.0,
 'othername': ['I Am Somebody'],
 'rate': 7.4,
 'showtime': 2015.0,
 'title': '我是路人甲',
 'url': 'http://movie.douban.com/subject/25746375/'
}
 """

"""

movie [] {cover,district,id,language,length,othername,rate,showtime,title,url} 

category_of -> category
language_of -> language
district_of -> district
alias_of -> othername


person [profession:actor|director|composer]

acted directed composed

category [name:剧情|喜剧]

"""


def peek():
    with open('./dbmovies.json') as f:
        s = f.read()
        dic = json.loads(s)
    return dic


def add_movie(tx, item):
    # 创建 movie
    cover = "" if item.get('cover', None) is None else item.get('cover', "")
    mid = 0 if item.get('id', None) is None else item.get('id', 0)
    length = 0 if item.get('length', None) is None else item.get('length', 0)
    rate = 0 if item.get('rate', None) is None else item.get('rate', 0)
    showtime = 0 if item.get('showtime', None) is None else item.get('showtime', 0)
    title = "" if item.get('title', None) is None else item.get('title', "")

    category = [] if item.get('category', []) is None else item.get('category', [])

    language = [] if item.get('language', []) is None else item.get('language', [])

    district = [] if item.get('district', []) is None else item.get('district', [])

    alias = [] if item.get('othername', []) is None else item.get('othername', [])

    part1 = f"""
    CREATE (m:Movie {{ cover: '{cover.replace("'", '"')}', id: {mid}, length: {length}, rate: {rate}, title: '{title.replace("'", '"')}' }} )"""

    part2 = f"""
    MERGE (y:Year {{ value: {showtime} }}) 
    MERGE (m)-[:SHOWED]->(y)"""

    count1 = 1
    ps1 = ""
    for it in category:
        part3 = f"""
            MERGE (c{count1}:Category {{ name: '{it.replace("'", '"')}' }}) 
            MERGE (m)-[:CATEGORY_OF]->(c{count1})"""
        ps1 += part3
        count1 += 1

    count2 = 1
    ps2 = ""
    for it in language:
        part3 = f"""
            MERGE (l{count2}:Language {{ name: '{it.replace("'", '"')}' }}) 
            MERGE (m)-[:LANGUAGE_OF]->(l{count2})"""
        ps2 += part3
        count2 += 1

    count3 = 1
    ps3 = ""
    for it in district:
        part3 = f"""
            MERGE (d{count3}:District {{ name: '{it.replace("'", '"')}' }}) 
            MERGE (m)-[:DISTRICT_OF]->(d{count3})"""
        ps3 += part3
        count3 += 1

    count4 = 1
    ps4 = ""
    for it in alias:
        part3 = f"""
            MERGE (a{count4}:Alias {{ name: '{it.replace("'", '"')}' }}) 
            MERGE (m)-[:ALIAS_OF]->(a{count4})"""
        ps4 += part3
        count4 += 1

    count = 1
    ps = ""
    if mid is not None:
        actor = [] if item.get('actor', []) is None else item.get('actor', [])
        for name in actor:
            part3 = f"""
            MERGE (p{count}:Person {{ name: '{name.replace("'", '"')}' }}) 
            MERGE (p{count})-[:ACTED]->(m)"""
            count += 1
            ps += part3

        composer = [] if item.get('composer', []) is None else item.get('composer', [])
        for name in composer:
            part3 = f"""
                    MERGE (p{count}:Person {{ name: '{name.replace("'", '"')}' }}) 
                    MERGE (p{count})-[:COMPOSED]->(m)"""
            count += 1
            ps += part3

        director = [] if item.get('director', []) is None else item.get('director', [])
        for name in director:
            part3 = f"""
                    MERGE (p{count}:Person {{ name: '{name.replace("'", '"')}' }}) 
                    MERGE (p{count})-[:DIRECTED]->(m)"""
            count += 1
            ps += part3

    query = part1 + part2 + ps1 + ps2 + ps3 + ps4 + ps
    print("one")
    tx.run(query)


if __name__ == '__main__':
    data = peek()
    driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "123456"))

    with driver.session() as session:
        # res = session.run("MATCH (m:Movie {title: $title}) RETURN m", {"title": "撒迦利亚"})
        # sin = res.single()
        # print(sin)
        for item in data:
            session.write_transaction(add_movie, item)
    driver.close()
